<?php
namespace app\common\controller;
use think\Controller;
use think\facade\Cache;

class Task extends Controller 
{
	/**
	* 路由配置 task/open
	* 开启定时任务
	*/
	public function open(){
		try {
			$myarr = include "./application/event.php";
			$total = 0; $errNum = 0; $suecNum = 0;
			foreach ($myarr['listen'] as $key => $value) {
				$value = str_replace("\\","/",$value); 
				if( $key && $value && $this->verifyTime($key) ){
					foreach( $value as $k => $api ){
						$result = action($api);
						$total = $total+1;
						if($result !== false){
							$suecNum = $suecNum+1;
						}else{
							$errNum = $errNum+1;
						}
					}
				}
			}
			return 'total: '.$total.' = sucess: '.$suecNum.' = error: '. $errNum.'  ';
		} catch (\Exception $e) {
			return 'fail--'. $e->getMessage();
        }
	}
	
	//效验时间
	private function verifyTime($key){
		$cachename = 'system_task_time_log'.$key;
		$cacheTime = Cache::get($cachename);
		$time = str_replace("task_","",$key);
		//按秒
	    if (filter_var($time, FILTER_VALIDATE_INT) !== false && !$cacheTime) {
			Cache::set($cachename,$time,$time);
			return true;
	    }
		//按天
		if (strstr($key,"d") && !$cacheTime) {
			$time = str_replace("task_d_","",$key);
			if($time < date("H")){
				Cache::set($cachename,$time,86400);
				return true;
			}
	    }
		//每周
		if (strstr($key,"w") && !$cacheTime) {
			$time = str_replace("task_w_","",$key);
			if($time == date("w")){
				Cache::set($cachename,$time,86400);
				return true;
			}
	    }
		//每月
		if (strstr($key,"m") && !$cacheTime) {
			$time = str_replace("task_m_","",$key);
			if($time == date("d") && date("H:i:s") >= '00:01:00' && date("H:i:s") <= '00:05:00'){
				Cache::set($cachename,$time,86400);
				return true;
			}
	    }
		return false;
	}
}



